<template>
  <div class="upload-box">
    <el-upload action="#"
               :http-request="handleUpload"
               list-type="picture"
               :limit="1"
               :before-upload="beforeAvatarUpload"
               :on-preview="handlePictureCardPreview"
               :on-remove="handleRemove">
        <div class="upload-icon" ref="uploadRf">
          <i class="iconfont icon-icon-mianxing_fuzhi_shangchuan"></i>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "upload",
  props: {
    BizID: {
      type: String
    }
  },
  watch: {
    BizID: {
      handler (newval, oldval) {
        // console.log("newval: ", newval)
        this.bizId = newval;
      },
      immediate: true
    }
  },
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      bizId: '',
      count: 0,
      avaliableTypes: ["image/jpeg", "image/png", "image/jpg"]
    }
  },
  methods: {
    handleRemove (file, fileList) {
      this.count--;
      if (fileList.length == 0) {
        this.$refs.uploadRf.style.display = 'inline-block';
      }
      // console.log(file, fileList);
    },
    beforeAvatarUpload (file) {
      if (this.count > 0) {
        this.$message.error("只能上传一张图片");
        return false;
      }
      this.count++;
      const isJPG = this.avaliableTypes.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUpload (fileObj) {
      console.log(fileObj)
      this.$emit("uploadFile", fileObj, this.bizId,(res)=>{
        // console.log("上传成功: ",res);
        if(res){
          this.handleSuccess();
        }
      });
    },
    handleSuccess (res) {
      // console.log("触发上传成功回调")
      this.$refs.uploadRf.style.display = 'none';
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-icon{
  width: 140px;
  height: 140px;
  border-radius: 10px;
  border: 4px dotted #9cdcfe;
  display: flex;
  justify-content: center;
  align-items: center;
  .iconfont{
    font-size: 40px;
  }
}
</style>